<template>
  <div class="login">
    <!-- 导航条 -->
    <van-notice-bar
      left-icon="volume-o"
      text="在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准。"
    />
    <van-nav-bar title="登录" />
    <!-- 通过校验点击提交才能发送请求 -->
    <van-form @submit="login">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入你的手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        type="number"
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userlogin } from '@/api/user'
export default {
  name: 'Login',

  data() {
    return {
      mobile: '',
      isLoading: false,
      code: '246810',
      rules: {
        // 手机号校验规则
        mobile: [
          {
            mobile: true,
            message: '手机号不能为空'
          },
          {
            // 手机号正则
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            // 纯数字
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    // try catch try里的代码时钟会执行    try代码错误 catch会捕获
    async login() {
      this.isLoading = true
      try {
        const res = await userlogin(this.mobile, this.code)

        // 保存token
        this.$store.commit('user/setToken', res.data)

        console.log(res.data)
        this.$toast.success('登录成功')
      } catch {
        this.$toast.success('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>
<style scoped lang="less"></style>
